package com.zb.zeus.common.core.autoconfig;

import com.zb.zeus.common.core.ZeusVersion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 宙斯默认配置监听器
 *
 * @author fujianjian
 * @date 2022/1/12 17:38
 **/
public class ZeusApplicationEnvironmentProcessor implements EnvironmentPostProcessor {
    private static final String ZEUS_DEFAULT_PROPERTIES_NAME = "zeusApplicationDefaultProperties";
    private static final String STASH_URI_PATTERN = "STASH_URI";
    private static final String IP_PATTHERN = "LOCAL_IP";

    private static final BiConsumer<String, String> systemPropertySetter = (name, value) -> {
        if (System.getProperty(name) == null && value != null) {
            System.setProperty(name, value);
        }
    };

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) {
        if (!env.containsProperty(ZEUS_DEFAULT_PROPERTIES_NAME)) {
            Map<String, Object> defaultZeusProp = new HashMap<>();
            defaultZeusProp.put("spring.cloud.nacos.config.file-extension",
                    env.resolvePlaceholders("${spring.cloud.nacos.config.file-extension:yaml}"));
            defaultZeusProp.put("spring.cloud.nacos.config.encode", "UTF-8");
            int cfgCnt = 0, idxCnt = 0;
            String activeProfiles = env.resolvePlaceholders("${spring.profiles.active:dev}");
            String defaultCfgName = String.format("application-%s.yml", activeProfiles);
            for (; ; ) {
                String value = env.resolvePlaceholders(String.format("${spring.cloud.nacos.config.shared-configs[%d]:}", cfgCnt));
                if (StringUtils.isEmpty(value)) {
                    break;
                }
                if (StringUtils.equals(value, defaultCfgName)) {
                    cfgCnt++;
                    continue;
                }
                defaultZeusProp.put(String.format("spring.cloud.nacos.config.shared-configs[%d]", idxCnt), value);
                cfgCnt++;
                idxCnt++;
            }
            defaultZeusProp.put(String.format("spring.cloud.nacos.config.shared-configs[%d]", idxCnt), defaultCfgName);
            String stashUri = env.resolvePlaceholders("${zeus.log.stash.url:}");
            stashUri = StringUtils.isNotEmpty(stashUri) ? stashUri : StringUtils.equals(activeProfiles, "prod") ? "127.0.0.1" : "10.88.1.227:4560";
            String mpBannar = env.resolvePlaceholders("${mybatis-plus.global-config.banner:false}");
            defaultZeusProp.put("zeus.log.stash.url", stashUri);
            defaultZeusProp.put("zeus.version", ZeusVersion.getVersion());
            defaultZeusProp.put("mybatis-plus.global-config.banner", mpBannar);

            if (System.getProperty(STASH_URI_PATTERN) == null) {
                System.setProperty(STASH_URI_PATTERN, stashUri);
            }
            setSystemProperty(STASH_URI_PATTERN, stashUri);
            setSystemProperty(IP_PATTHERN, getLocalIP());

            env.getPropertySources().addFirst(new MapPropertySource(ZEUS_DEFAULT_PROPERTIES_NAME, defaultZeusProp));
        }

    }

    private String getLocalIP() {
        String localip;
        try {
            localip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            localip = "127.0.0.1";
        }
        return localip;
    }
    protected final void setSystemProperty(String name, String value) {
        systemPropertySetter.accept(name, value);
    }


}

